package com.example.zkweixiu.app.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Layout;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MapViewLayoutParams;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.route.BaiduMapRoutePlan;
import com.baidu.mapapi.utils.route.RouteParaOption;
import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonAdapter;
import com.example.zkweixiu.app.MainActivity;
import com.example.zkweixiu.app.R;
import com.example.zkweixiu.app.bean.TaskBean;
import com.example.zkweixiu.app.pro.PublicPro;
import com.google.gson.Gson;
import com.vondear.rxtool.RxLocationTool;
import com.vondear.rxtool.RxTextTool;
import com.vondear.rxtool.model.Gps;
import com.yanzhenjie.sofia.Sofia;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.Iterator;

import okhttp3.Call;

/**
 * 维修任务
 */
public class TaskActivity extends AppCompatActivity implements LocationListener {

    private TaskBean taskBean;
    private TextView workbox; //工具箱
    private Context context;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 200:
                    initView();
                    list_task.setAdapter(commonAdapter);

                    sw_out.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                        @Override
                        public void onRefresh() {
                            //
                            getDataList(1, 100);
                        }
                    });
                    if (sw_out != null) {
                        sw_out.setRefreshing(false);
                    }

/*                    if (taskBean == null || taskBean.getData() == null || taskBean.getData().getRows().size() == 0) {
                        if (sw_out != null) {
                            sw_out.setRefreshing(false);
                        }

                        if (commonAdapter != null){
                            commonAdapter.notifyDataSetChanged();
                        }
                        Toast.makeText(context, "暂无任务", Toast.LENGTH_SHORT).show();
                        return;
                    } else {

                    }*/
                    break;
            }
        }
    };
    private CommonAdapter<TaskBean.DataBean.RowsBean> commonAdapter;
    private ListView list_task;
    private SwipeRefreshLayout sw_out;
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private double longitude = 0;
    private double latitude = 0;
    private LocationManager locationManager;
    private TextView textView;

    private void initView() {
        /*
         */
        commonAdapter = new CommonAdapter<TaskBean.DataBean.RowsBean>(context, R.layout.task_item, taskBean.getData().getRows()) {
            @Override
            public void onUpdate(final BaseAdapterHelper helper, final TaskBean.DataBean.RowsBean item, int position) {

                mMapView = helper.getView(R.id.bmapView);
                TextView tv_user_data = helper.getView(R.id.tv_user_data);

                RxTextTool.getBuilder("").setBold().setAlign(Layout.Alignment.ALIGN_CENTER).append(item.getUserName() + "的\"" + item.getSetAlias() + "\"设备").
                        setForegroundColor(Color.parseColor("#000000")).append("发生了").append(item.getWarCause()).setForegroundColor(Color.parseColor("#4070ff"))
                        .append("" + item.getOrdPeople() + "决定派您前往").append(item.getAddress()).setForegroundColor(Color.parseColor("#000000"))
                        .append("进行维修作业。").append("电话" + item.getUserPhone()).setForegroundColor(Color.parseColor("#000000")).into(tv_user_data);


                mMapView.showZoomControls(false);
                mBaiduMap = mMapView.getMap();
                // 开启定位图层
                mBaiduMap.setMyLocationEnabled(true);
                // 开启室内图
                mBaiduMap.setIndoorEnable(true);

                LatLng ll = new LatLng(Double.parseDouble(item.getLatitude()), Double.parseDouble(item.getLongitude()));
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                //定义Maker坐标点
                LatLng point = new LatLng(Double.parseDouble(item.getLatitude()), Double.parseDouble(item.getLongitude()));
//构建Marker图标
                BitmapDescriptor bitmap = BitmapDescriptorFactory
                        .fromResource(R.drawable.faultlog);  //地图上的点
//构建MarkerOption，用于在地图上添加Marker
                OverlayOptions option = new MarkerOptions()
                        .position(point)
                        .icon(bitmap);
//在地图上添加Marker，并显示
                mBaiduMap.addOverlay(option);


                helper.setOnClickListener(R.id.tv_map, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {


                        if (latitude == 0 || longitude == 0) {
                            gpsCheck();
                            Toast.makeText(context, "正在定位", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        textView = helper.getView(R.id.tv_map);
                        textView.setEnabled(false);

                        //定义起终点坐标（天安门和百度大厦）
                        LatLng startPoint = new LatLng(latitude, longitude);
                        LatLng endPoint = new LatLng(Double.parseDouble(item.getLatitude()), Double.parseDouble(item.getLongitude()));

                        //构建RouteParaOption参数以及策略
                        //也可以通过startName和endName来构造
                        RouteParaOption paraOption = new RouteParaOption()
                                .startPoint(startPoint)
                                .endPoint(endPoint)
                                .busStrategyType(RouteParaOption.EBusStrategyType.bus_recommend_way);
                        //调起百度地图
                        try {
                            BaiduMapRoutePlan.openBaiduMapTransitRoute(paraOption, context);
                        } catch (Exception e) {
                            e.printStackTrace();
                            textView.setEnabled(true);
                        }
                        //调起结束时及时调用finish方法以释放相关资源
                        BaiduMapRoutePlan.finish(context);
                    }
                });

                helper.setOnClickListener(R.id.workbox, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent  intent = new Intent(context, WorkboxActivity.class);
                        startActivity(intent);
                    }
                });


            }
        };
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (textView != null) {
            textView.setEnabled(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        if (mMapView != null) {
            mMapView.onDestroy();

        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task);
        Sofia.with(TaskActivity.this).statusBarDarkFont().statusBarBackground(Color.parseColor("#F5F6F9"));
        context = TaskActivity.this;
        list_task = (ListView) findViewById(R.id.list_task);
        View iv_fanhui2 = findViewById(R.id.iv_fanhui2);
        sw_out = findViewById(R.id.sw_out);
       // workbox = findViewById(R.id.workbox); //工具箱
/*       // workbox.setOnClickListener((View.OnClickListener) this); //工具箱

        workbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });*/
        locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);

        sw_out.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //
                getDataList(1, 100);
            }
        });
        gpsCheck();
        getDataList(1, 100);

        iv_fanhui2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }


    private void gpsCheck() {
        if (!RxLocationTool.isGpsEnabled(this)) {
            MaterialDialog.Builder builder = new MaterialDialog.Builder(this);
            MaterialDialog materialDialog = builder.title("GPS未打开").content("您需要在系统设置中打开GPS方可采集数据").positiveText("去设置")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            RxLocationTool.openGpsSettings(context);
                        }
                    }).build();
            materialDialog.setCanceledOnTouchOutside(false);
            materialDialog.setCancelable(false);
            materialDialog.show();
        } else {
            getLocation();
        }
    }


    private void getLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions((MainActivity) context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 13000, 0, this);
        locationManager.addGpsStatusListener(new GpsStatus.Listener() {
            @Override
            public void onGpsStatusChanged(int event) {
                switch (event) {
                    case GpsStatus.GPS_EVENT_STARTED:
                        System.out.println("GPS_EVENT_STARTED");
                        break;
                    case GpsStatus.GPS_EVENT_FIRST_FIX:
                        System.out.println("GPS_EVENT_FIRST_FIX");
                        break;
                    case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                        System.out.println("GPS_EVENT_SATELLITE_STATUS");
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        GpsStatus gpsStatus = locationManager.getGpsStatus(null);
                        Iterable<GpsSatellite> gpsSatellites = gpsStatus.getSatellites();
                        int count = 0;
                        Iterator iterator = gpsSatellites.iterator();
                        while (iterator.hasNext()) {
                            count++;
                            iterator.next();
                        }
                        //  mGpsCount.setText(count + "");
                        break;
                    case GpsStatus.GPS_EVENT_STOPPED:
                        System.out.println("GPS_EVENT_STOPPED");
                        //gpsState.setText("已停止定位");
                        break;
                }
            }
        });
    }

    private void getDataList(int page, int rows) {
        OkHttpUtils
                .get()
                .url(PublicPro.TASK_LIST)
                .addParams("wx_uuid", PublicPro.userBean.getData().getGuaUuid()) //获取用户uuid
                .addParams("token", PublicPro.userBean.getData().getGuaToken()) //获取token
                .addParams("page", page + "")
                .addParams("rows", rows + "")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (sw_out != null) {
                            sw_out.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("HomeFragment1", response);

                        taskBean = new Gson().fromJson(response, TaskBean.class);

                        if (taskBean.getStatus() == 200) {
                            handler.sendEmptyMessage(200);
                        } else {
                            if (sw_out != null) {
                                sw_out.setRefreshing(false);
                            }
                            Toast.makeText(TaskActivity.this, taskBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                });
    }

    @Override
    public void onLocationChanged(Location location) {
        Gps gps = RxLocationTool.GCJ02ToBD09(location.getLongitude(), location.getLatitude());
        longitude = gps.getLongitude();
        latitude = gps.getLatitude();
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
}
